using UnityEngine;

namespace UndergroundSurvival.Rooms
{
    public class PowerPlantRoom : BaseRoom
    {
        [Header("Power Plant Settings")]
        [SerializeField] private float powerGenerationRate = 1f;
        [SerializeField] private float fuelConsumptionRate = 0.1f;
        [SerializeField] private float maintenanceCost = 0.05f;
        [SerializeField] private float efficiency = 1f;

        private float currentEfficiency = 1f;
        private float maintenanceTimer = 0f;
        private const float MAINTENANCE_INTERVAL = 300f; // 5分钟需要维护一次

        protected override void Update()
        {
            base.Update();

            if (!isBuilt || !isFunctioning) return;

            // 检查维护状态
            maintenanceTimer += Time.deltaTime;
            if (maintenanceTimer >= MAINTENANCE_INTERVAL)
            {
                currentEfficiency *= 0.9f; // 效率随时间降低
                maintenanceTimer = 0f;
            }

            // 消耗燃料并发电
            if (ResourceManager.Instance != null)
            {
                float actualFuelConsumption = fuelConsumptionRate * currentEfficiency;
                if (ResourceManager.Instance.ModifyResource(ResourceType.Fuel, -actualFuelConsumption * Time.deltaTime))
                {
                    // 成功消耗燃料，产生电力
                    float powerGenerated = powerGenerationRate * currentEfficiency * Time.deltaTime;
                    ResourceManager.Instance.ModifyResource(ResourceType.Power, powerGenerated);
                }
                else
                {
                    // 燃料不足，停止发电
                    isFunctioning = false;
                }
            }
        }

        public void PerformMaintenance()
        {
            if (ResourceManager.Instance != null)
            {
                if (ResourceManager.Instance.ModifyResource(ResourceType.Metal, -maintenanceCost))
                {
                    currentEfficiency = efficiency;
                    maintenanceTimer = 0f;
                    isFunctioning = true;
                }
            }
        }

        public override void OnRoomUpgraded()
        {
            base.OnRoomUpgraded();
            powerGenerationRate *= 1.5f;
            efficiency *= 1.2f;
            currentEfficiency = efficiency;
        }

        public float GetCurrentEfficiency()
        {
            return currentEfficiency;
        }

        public float GetMaintenanceProgress()
        {
            return 1f - (maintenanceTimer / MAINTENANCE_INTERVAL);
        }

        public bool NeedsMaintenance()
        {
            return currentEfficiency < efficiency * 0.8f;
        }
    }
} 